package com.yyp.test;

import com.yyp.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Test01 {

    @Test
    public void selectUserAll() throws IOException {
        //加载核心配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //获得sqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //获得sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行sql语句
        List<User> userList = sqlSession.selectList("userMapper.selectUserAll");
        //打印结果
        System.out.println(userList);
        //释放资源
        sqlSession.close();

    }


    @Test
    public void add() throws IOException {
        //加载核心配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //获得sqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //获得sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行sql语句
        User user = new User();
        user.setUsername("魏林杜");
        user.setPassword("123456");
        int result = sqlSession.insert("userMapper.add",user);
        //提交增加事务
        sqlSession.commit();
        //打印结果
        System.out.println(result);
        //释放资源
        sqlSession.close();

    }

    @Test
    public void update() throws IOException {
        //加载核心配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //获得sqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //获得sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行sql语句
        User user = new User();
        user.setId(6);
        user.setUsername("cjk");
        user.setPassword("6666666");
        int update = sqlSession.update("userMapper.update",user);
        //提交增加事务
        sqlSession.commit();
        //打印结果
        System.out.println(update);
        //释放资源
        sqlSession.close();

    }


    @Test
    public void delete() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory  sqlSessionFactory  = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession  = sqlSessionFactory.openSession();
        int delete = sqlSession.delete("userMapper.delete", 8);
        System.out.println(delete);
        sqlSession.commit();
        sqlSession.close();


    }
}

